package com.neusmart.fs.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.neusmart.fs.F;
import com.neusmart.fs.R;
import com.neusmart.fs.adapter.MyzoneUserPicAdapter;
import com.neusmart.fs.adapter.UpDataEducationPicPicAdapter;
import com.neusmart.fs.adapter.UpDataIdentityPicAdapter;
import com.neusmart.fs.constants.API;
import com.neusmart.fs.constants.Key;
import com.neusmart.fs.constants.RequestCode;
import com.neusmart.fs.model.MParam;
import com.neusmart.fs.model.UploadNotify;
import com.neusmart.fs.result.ResultGetUploadNotify;
import com.neusmart.fs.util.ImageLoaderUtil;
import com.neusmart.fs.view.NoScrollGridView;
import com.neusmart.fs.view.alertview.AlertView;
import com.neusmart.fs.view.alertview.OnItemClickListener;
import com.neusmart.fs.view.dialog.OnHintListener;
import com.neusmart.fs.view.photoview.Info;
import com.neusmart.fs.view.photoview.PhotoView;
import com.neusmart.fs.view.viewpagerindicator.CirclePageIndicator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

public class ChangeUserMassageLastActivity extends UploadPhotoBaseActivity implements View.OnClickListener,MyzoneUserPicAdapter.OnGalleryPhotoEditActionListener,UpDataIdentityPicAdapter.OnSelectPhotoActionListener,UpDataEducationPicPicAdapter.OnSelectPhotoActionListener,OnItemClickListener {
    //
    AlphaAnimation in = new AlphaAnimation(0, 1);
    AlphaAnimation out = new AlphaAnimation(1, 0);
    private EditText identityNo;
    private Bundle bundle;
    private AlertView mAlertView;
    protected List<UploadNotify> mUploadNotifies;
    private List<String> imagePathList;
    private List<String> educationPathList;
    private UpDataIdentityPicAdapter photoAdapter;
    private UpDataEducationPicPicAdapter educationphotoAdapter;
    private NoScrollGridView photoGridView;
    private NoScrollGridView educationPhotoGridView;
    private boolean Updataidentity=true;
    private List<String> mList;
    private List<String> eduPicList;
    private String edu_bg_photo;
    private PhotoView mPhotoView;
    //
    private DisplayImageOptions options;
    private ViewPager mPhotoPager;
    private View mParent, mBg;
    private ProgressBar mProgressBar;
    private CirclePageIndicator mIndicator;
    //
    private ArrayList<PhotoView> viewContainer = new ArrayList<>();
    private Info infoTo;
    private int currentPos;
    private  String cardNo;
    private String url="http://fshome.oss-cn-beijing.aliyuncs.com/identity/2017-05-20/d703b4503cb911e79f3bc5bd6966a756.jpg";
    @Override
    protected int getLayoutResID() {
        return R.layout.activity_change_user_massage_last;
    }
    @Override
    protected void init() {
        loadExtraData();
        initView();
        setContent();
        setListener();
    }

    private void intoBundle() {
        if (F.mUserInfo.getIdentity_photo().size()>=1){
            if (F.mUserInfo.getApproveState()==2){
                mList.set(0,F.mUserInfo.getIdentity_photo().get(0));
            }
        }
        bundle.putString("identityNo",identityNo.getText().toString());
        bundle.putStringArrayList("identity_photo", (ArrayList<String>) mList);
        bundle.putString("edu_bg_photo",edu_bg_photo);
    }

    private void loadExtraData() {
        bundle = getIntent().getExtras();
        if (bundle == null)
            return;
    }

    private void setListener() {
        int[] resIds = {R.id.my_data_btn_back,R.id.btn_finish,R.id.uploadpic_identity,R.id.uploadpic_education};
        for (int id : resIds)
            findViewById(id).setOnClickListener(this);
        photoAdapter.setOnSelectPhotoActionListener(this);
        educationphotoAdapter.setOnSelectPhotoActionListener(this);
    }

    private void setContent() {
        if (F.mUserInfo.getIdentity_no()!=null){
            identityNo.setText(F.mUserInfo.getIdentity_no()+"");
        }else if (bundle.getString("cardNo")!=null){
            identityNo.setText(bundle.getString("cardNo"));
        }
        if (F.mUserInfo.getApproveState()==2){//通过身份认证的用户并且通过了认证
            //mList.add(url);//占位图
            mList.addAll(F.mUserInfo.getIdentity_photo());//身份证照片集合
            mList.set(0,url);
        }else {
            mList.addAll(F.mUserInfo.getIdentity_photo());//身份证照片集合
        }
        photoAdapter.notifyDataSetChanged();
        if (F.mUserInfo.getEdu_bg_photo()!=null){
            eduPicList.add(F.mUserInfo.getEdu_bg_photo());
            educationphotoAdapter.notifyDataSetChanged();
        }
    }

    private void initView() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.head_default)
                .showImageForEmptyUri(R.drawable.head_default)
                .showImageOnFail(R.drawable.head_default).cacheInMemory(true)
                .cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        //
        mPhotoPager = (ViewPager) findViewById(R.id.pager);
        mPhotoPager.setPageMargin((int) (getResources().getDisplayMetrics().density * 15));
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
        //时间同PhotoView
        in.setDuration(500);//
        out.setDuration(500);//
        mParent = findViewById(R.id.parent);
        mBg = findViewById(R.id.bg);
        //
        mUploadNotifies=new ArrayList<>();
        mList=new ArrayList<>();//身份证件url的集合
        eduPicList=new ArrayList<>();
        imagePathList = new ArrayList<>();
        educationPathList=new ArrayList<>();
        identityNo= (EditText) findViewById(R.id.identity_change);
        //F.mUserInfo.getApproveState()==2
        photoAdapter = new UpDataIdentityPicAdapter(mList,this);
        educationphotoAdapter = new UpDataEducationPicPicAdapter(eduPicList,this);
        photoGridView= (NoScrollGridView) findViewById(R.id.grid_identity_pics);
        educationPhotoGridView= (NoScrollGridView) findViewById(R.id.grid_education_pics);
        photoGridView.setAdapter(photoAdapter);
        educationPhotoGridView.setAdapter(educationphotoAdapter);
        //mAlertView = new AlertView(null, null, "取消", null, new String[]{"拍照", "从手机选择"}, this, AlertView.Style.ActionSheet,this);
    }

    @Override
    public void onClick(View v) {
        if (getCurrentFocus() != null)//隐藏软键盘
            hideSoftInput();
        switch (v.getId()) {
            case R.id.my_data_btn_back:
                onBackPressed();
                break;
            case R.id.btn_finish:
                if (identityNo.getText().toString().isEmpty()){
                    showToast("请输入正确的身份证号");
                    return;
                }
                if (mList.size()==0){
                    showToast("请上传身份证照片");
                    return;
                }
                if (F.mUserInfo.getUser_status()==0){//新用户
                    if (F.mUserInfo.getApproveState()==2){
                        if (identityNo.getText().toString().equals(F.mUserInfo.getIdentity_no())){
                            loadData(API.UPDATE_PROFILES, true);
                        }else if (!identityNo.getText().toString().equals(F.mUserInfo.getIdentity_no())){
                            if (mList.size()>1){
                                loadData(API.UPDATE_PROFILES, true);
                            }else {
                                showHintDialog("身份证号与身份证系统认证信息不匹配，请上传您的身份证照片", new OnHintListener() {
                                    @Override
                                    public void onHint() {
                                        onAddPhoto();
                                    }
                                });
                            }
                        }
                    }else {
                        loadData(API.UPDATE_PROFILES, true);
                    }
                }else {
                    intoBundle();
                    if (F.mUserInfo.getApproveState()==2){
                        if (identityNo.getText().toString().equals(F.mUserInfo.getIdentity_no())){
                            switchActivity(ChangeUserMassageCommitActivity.class,bundle);
                        }else if (!identityNo.getText().toString().equals(F.mUserInfo.getIdentity_no())){
                            if (mList.size()>1){
                                switchActivity(ChangeUserMassageCommitActivity.class,bundle);
                            }else {
                                showHintDialog("输入的身份证号与认证不匹配，请上传相应人身份证照片", new OnHintListener() {
                                    @Override
                                    public void onHint() {
                                        onAddPhoto();
                                    }
                                });
                            }
                        }
                    }else {
                        switchActivity(ChangeUserMassageCommitActivity.class,bundle);
                    }
                }
                    //需要判断是否要去上传头像
                    /*if (F.mUserInfo.getHead_url()==null){
                        switchActivity(UpDataUserPicActivity.class,bundle);
                    }else {

                        switchActivity(ChangeUserMassageCommitActivity.class,bundle);
                    }*/
                break;
            case R.id.uploadpic_identity:
                Updataidentity=true;
                if (mList.size()>=2){
                    showToast("身份证照片最多上传两张");
                }else {
                    onAddPhoto();
                }
                break;
            case R.id.uploadpic_education:
                Updataidentity=false;
                onAddPhoto();
            default:
                break;
        }

    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // EventBus.getDefault().unregister(this);
    }
    @Override
    protected void initParams(MParam param) {
        switch (param.getApi()) {
            case UPLOAD_NOTIFY:
                param.addParam("fileUploads", fileUploads);
                break;
            case UPDATE_PROFILES:
                if (F.mUserInfo.getIdentity_photo().size()>=1){
                    mList.set(0,F.mUserInfo.getIdentity_photo().get(0));
                }
                param.addParam("identity_no", identityNo.getText().toString());
                param.addParam("identity_photo", mList);//身份
                if (edu_bg_photo!=null){//学历
                    param.addParam("edu_bg_photo", edu_bg_photo);
                }
                param.addParam("needUpdateStatus",false);//1
                break;
            default:
                break;
        }
    }
    @Override
    protected void disposeResult(API api, String response) {
        if (response == null)
            return;
        switch (api) {
            case UPLOAD_NOTIFY:
                ResultGetUploadNotify resultGetUploadNotify = fromJson(response, ResultGetUploadNotify.class);
                if (!resultGetUploadNotify.isSuccess()) {
                    showToast(resultGetUploadNotify.getFriendlyMessage());
                    return;
                }
                uploadNotifies = resultGetUploadNotify.getData().getFiles();
                uploadNextPhoto(false);
                break;
            case UPDATE_PROFILES:
                intoBundle();
                switchActivity(ChangeUserMassageCommitActivity.class,bundle);
                break;
            default:
                break;
        }
    }

    private void processPhotosAndUpload() {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showLoadingDialog();
            }

            @Override
            protected Void doInBackground(Void... params) {
                for (String path : imagePathList)
                    compressPhoto(path);//先进行图片压缩
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                dismissLoadingDialog();
                //上传上报通知
                loadData(API.UPLOAD_NOTIFY, true);
            }
        }.execute();
    }

    @Override
    protected int getMaxPhotoNum() {
        if (Updataidentity){
            return 2-mList.size();
        }else if (Updataidentity==false){
            return 1;
        }
        return 0;
    }

    @Override
    protected void onFinishUpload() {//上传成功的返回
        if (Updataidentity){//身份证
            for (int i=0;i<uploadNotifies.size();i++){
                mList.add(uploadNotifies.get(i).getUrl());
            }
            if (F.mUserInfo.getApproveState()==2){
                mList.set(0,url);
            }
            photoAdapter.notifyDataSetChanged();
        }else if (Updataidentity==false){
            eduPicList.clear();
            edu_bg_photo= uploadNotifies.get(uploadNotifies.size()-1).getUrl();
            eduPicList.add(edu_bg_photo);
            educationphotoAdapter.notifyDataSetChanged();
        }
        imagePathList.clear();
        clearTemp();
    }


    @Override
    public void onPhotoDelete(int position) {
        mList.remove(position);
        if (F.mUserInfo.getApproveState()==2){
            if (F.mUserInfo.getIdentity_photo().size()>=1){
                mList.set(0,url);
            }
        }
        photoAdapter.notifyDataSetChanged();
    }

    @Override
    public void onAddPhoto() {
        mAlertView = new AlertView(null, null, "取消", null, new String[]{"拍照", "从手机选择"}, this, AlertView.Style.ActionSheet,this);
        mAlertView.show();
    }

    @Override
    public void onItemClick(Object o, int position) {
        if (position != AlertView.CANCELPOSITION) {
            switch (position) {
                case 0:
                    takePhoto();
                    break;
                case 1:
                    selectPhoto();
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case RequestCode.CAPTURE_PHOTO://拍照
                    addCapturePhoto();
                    break;
                case RequestCode.SELECT_PHOTO://相册
                    addSelectPhoto(data);
                    break;
                default:
                    break;
            }
        }
    }

    private void addCapturePhoto() {
        if (Updataidentity){//上传身份证
            if (imagePathList.contains(UpDataIdentityPicAdapter.IMAGE_ADD_URL)){
                imagePathList.remove(UpDataIdentityPicAdapter.IMAGE_ADD_URL);
            }
            //最多2张
            if (imagePathList.size() == 2) {
                showToast("最多可添加" + 2 + "张图片");
                return;
            }
            imagePathList.add(capturePhotoPath);
            if (imagePathList.size() < getMaxPhotoNum() && !imagePathList.contains(UpDataIdentityPicAdapter.IMAGE_ADD_URL))
                imagePathList.add(UpDataIdentityPicAdapter.IMAGE_ADD_URL);
            photoAdapter.notifyDataSetChanged();
            processPhotosAndUpload();

        }else if (Updataidentity==false){
            if (imagePathList.contains(UpDataIdentityPicAdapter.IMAGE_ADD_URL))
                imagePathList.remove(UpDataIdentityPicAdapter.IMAGE_ADD_URL);
            imagePathList.add(capturePhotoPath);
            if (imagePathList.size() < getMaxPhotoNum() && !imagePathList.contains(UpDataIdentityPicAdapter.IMAGE_ADD_URL))
                imagePathList.add(UpDataIdentityPicAdapter.IMAGE_ADD_URL);
            //educationphotoAdapter.notifyDataSetChanged();
            processPhotosAndUpload();
        }

    }

    private void addSelectPhoto(Intent intent) {
        int code = intent.getIntExtra(Key.SELECT_PHOTO_CODE, -1);
        if (code != 100)
            return;
        List<String> paths = intent.getStringArrayListExtra(Key.SELECT_PHOTO_PATH);
        //String[] pathArray = new String[paths.size()];
        //paths.toArray(pathArray);
        if (imagePathList.contains(UpDataIdentityPicAdapter.IMAGE_ADD_URL))
            imagePathList.remove(UpDataIdentityPicAdapter.IMAGE_ADD_URL);
        //添加，去重
        boolean hasUpdate = false;
        for (String path : paths) {
            if (!imagePathList.contains(path)) {
                //最多2张
                if (imagePathList.size() == 2) {
                    showToast("最多可添加" + 2 + "张图片");
                    break;
                }
                imagePathList.add(path);
                hasUpdate = true;
            }
        }
        if (imagePathList.size() < getMaxPhotoNum() && !imagePathList.contains(UpDataIdentityPicAdapter.IMAGE_ADD_URL))
            imagePathList.add(UpDataIdentityPicAdapter.IMAGE_ADD_URL);
        if (hasUpdate)
            processPhotosAndUpload();
    }

    @Override
    public void onViewIdentityPhoto(int index) {//浏览身份证照片
        if (F.mUserInfo.getApproveState()==2){
            if (F.mUserInfo.getIdentity_photo().size()>=1){
                mList.set(0,url);
            }
        }
        Info info = ((PhotoView) photoGridView.getChildAt(index).findViewById(R.id.item_select_photo_img)).getInfo();
        browsePhotos(mList,index,info);
    }

    @Override
    public void onDeleteEduPhoto(int index) {
        edu_bg_photo=null;
        eduPicList.remove(index);
        educationphotoAdapter.notifyDataSetChanged();
    }

    @Override
    public void onViewEduPhoto(int index) {//浏览学历证照片
        Info info1 = ((PhotoView) educationPhotoGridView.getChildAt(index).findViewById(R.id.item_select_photo_img)).getInfo();
        browsePhotos(eduPicList,index,info1);
    }

    /**
     * 查看图片
     *
     * @param photos
     * @param index
     */
    public void browsePhotos(final List<String> photos, int index, Info info) {
        infoTo = info;
        currentPos = index;
        viewContainer.clear();
        for (String photo : photos) {
            final PhotoView view = new PhotoView(this);
            view.enable();
            ImageLoaderUtil.display(photo, view,options,new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    mProgressBar.setVisibility(View.VISIBLE);
                }


                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                }
            });
            view.setScaleType(ImageView.ScaleType.FIT_CENTER);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBg.startAnimation(out);
                    view.animaTo(infoTo, new Runnable() {
                        @Override
                        public void run() {
                            mParent.setVisibility(View.GONE);
                        }
                    });
                }
            });
            viewContainer.add(view);
        }
        viewContainer.get(index).animaFrom(infoTo);
        mPhotoPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return photos.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewContainer.get(position));
                return viewContainer.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        });
        mPhotoPager.setCurrentItem(index);
        mIndicator.setViewPager(mPhotoPager);
        mParent.setVisibility(View.VISIBLE);
    }

}
